package com.leyou.search.scheduler;

import com.leyou.auth.client.AuthClient;
import com.leyou.search.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 服务token定时申请任务类
 */
@Component
@Slf4j
public class AppTokenScheduler{
    @Autowired
    private AuthClient authClient;
    @Autowired
    private JwtProperties jwtProps;

    private String appToken;//用于存储当前服务的服务token

    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L; //24小时

    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    /**
     * 定时任务服务token的方法
     */
    @Scheduled(fixedRate = TOKEN_REFRESH_INTERVAL)
    public void appToken(){

        while(true) {
            //1.远程调用获取服务token的方法
            try {
                appToken = authClient.authorization(
                        jwtProps.getApp().getServiceName(),
                        jwtProps.getApp().getSecret());

                log.info("【微服务鉴权】"+jwtProps.getApp().getServiceName()+"服务成功上线啦！");

                //如果服务token获取成，退出循环
                break;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("【微服务鉴权】获取服务token失败，原因：" + e.getMessage());
                //等待完之后再重试
                try {
                    Thread.sleep(TOKEN_RETRY_INTERVAL);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }

        }

    }

    /**
     * 该方法提供给外部获取当前服务token
     * @return
     */
    public String getAppToken() {
        return appToken;
    }
}
